<template>
  <div class="page-discount">
    <!-- 新版规范 -->
    <div class="discount-mod">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form
          ref="test-form"
          :inline="true"
          class="search-form"
          :model="searchForm"

          @submit.prevent
        >
          <div class="input-row">
            <el-form-item :label="$t('prodList.shopName') + ':'">
              <el-input
                v-model="searchForm.shopName"
                clearable
                :placeholder="$t('prodList.shopName')"
              />
            </el-form-item>
            <el-form-item :label="$t('groups.eventName') + ':'">
              <el-input
                v-model="searchForm.discountName"
                clearable
                :placeholder="$t('groups.eventName')"
              />
            </el-form-item>
            <el-form-item :label="$t('group.actStatus') + ':'">
              <el-select
                v-model="searchForm.status"
                clearable
                :placeholder="$t('group.actStatus')"
              >
                <el-option
                  v-for="item in searchForm.statusList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <div
                class="default-btn primary-btn"
                @click="onSearch(true)"
              >
                {{ $t('shopFeature.searchBar.search') }}
              </div>
              <div
                class="default-btn"
                @click="clearSearch"
              >
                {{ $t('product.reset') }}
              </div>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <!-- 搜索栏end -->
      <!-- 表格主体 -->
      <div class="main-container">
        <!-- 表格 -->
        <div class="table-con seckill-table">
          <el-table
            :data="dataList"
            header-cell-class-name="table-header"
            row-class-name="table-row-low"
            style="width: 100%"
          >
            <el-table-column
              prop="shopName"
              :label="$t('shop.storeName')"
              min-width="250"
            >
              <template #default="scope">
                <span class="table-cell-text">{{ scope.row.shopName }}</span>
              </template>
            </el-table-column>

            <el-table-column
              align="left"
              prop="discountName"
              :label="$t('groups.eventName')"
              min-width="240"
            >
              <template #default="scope">
                <span class="table-cell-text line-clamp-one">{{ scope.row.discountName }}</span>
              </template>
            </el-table-column>

            <el-table-column
              min-width="130"
              :label="$t('marketing.mobiltyDiagram')"
            >
              <template #default="scope">
                <div class="table-cell-image">
                  <ImgShow
                    :src="scope.row.mobilePic"
                    :img-alt="scope.row.prodName"
                  />
                </div>
              </template>
            </el-table-column>

            <el-table-column
              prop="startTime"
              :label="$t('coupon.startTime')"
              min-width="200"
            />

            <el-table-column
              prop="endTime"
              :label="$t('coupon.endTime')"
              min-width="200"
            />

            <el-table-column
              prop="status"
              :label="$t('group.actStatus')"
              min-width="120"
            >
              <template #default="scope">
                <div class="tag-text">
                  {{ [$t("seckill.close"), $t("seckill.open"), $t("groups.offlineViolation"),
                      $t('product.pendingReview')]
                    [scope.row.status] }}
                </div>
              </template>
            </el-table-column>

            <el-table-column
              align="center"
              :label="$t('crud.menu')"
              width="300"
              fixed="right"
            >
              <template #default="scope">
                <div class="text-btn-con">
                  <div
                    class="default-btn text-btn"
                    @click="showDiscountInfoHandle(scope.row.discountId)"
                  >
                    {{ $t('discount.viewActivities') }}
                  </div>
                  <div
                    class="default-btn text-btn"
                    @click="showProds(scope.row.discountId)"
                  >
                    {{ $t('prodList.lookOverProd') }}
                  </div>
                  <div
                    v-if="isAuth('platform:discount:update') && scope.row.status > 1"
                    class="default-btn text-btn"
                    @click="discountAuditHandle(scope.row.discountId)"
                  >
                    {{ scope.row.status === 2?$t("prodList.offShelfManage"):$t("product.pendingReview") }}
                  </div>
                  <div
                    v-if="isAuth('platform:discount:update') && scope.row.status<2"
                    class="default-btn text-btn"
                    @click="offlineDiscountHandle(scope.row)"
                  >
                    {{ $t('product.violation') }}
                  </div>
                  <div
                    class="default-btn text-btn"
                    @click="onDelete(scope.row.discountId)"
                  >
                    {{ $t('remindPop.delete') }}
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 分页 -->
        <el-pagination
          v-if="dataList.length"
          :current-page="page.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
          @size-change="onPageSizeChange"
          @current-change="onPageChange"
        />
      </div>
      <!-- 表格主体end -->
    </div>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdateRef"
    />
    <discount-info
      v-if="discountInfoVisible"
      ref="discountInfoRef"
      @refresh-select-prods="refreshChange"
    />
    <!-- 商品审核弹窗 -->
    <offline-audit
      v-if="discountAuditVisible"
      ref="discountAuditRef"
      select-url="/platform/discount/getOfflineHandleEventByDiscountId"
      update-url="/platform/discount/auditDiscount"
      @refresh-data-list="refreshChange"
    />
  </div>
</template>

<script setup>
import { isAuth } from '@/utils'
import { ElMessage, ElMessageBox } from 'element-plus'
import AddOrUpdate from './add-or-update.vue'
import DiscountInfo from './components/discount-info.vue'

onMounted(() => {
  getDataList()
})

let tempSearchForm = null // 保存上次点击查询的请求条件
const dataList = ref([])
const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
// 头部搜索表单
const searchForm = reactive({
  discountRule: 3,
  shopName: null,
  discountName: null,
  status: null,
  statusList: [
    {
      label: $t('seckill.close'),
      value: 0
    }, {
      label: $t('seckill.open'),
      value: 1
    }, {
      label: $t('groups.offlineViolation'),
      value: 2
    }, {
      label: $t('product.pendingReview'),
      value: 3
    }
  ]
})
const dataListLoading = ref(false)
/**
 * 获取数据列表
 * @param pageParam
 * @param newData
 */
const getDataList = (pageParam, newData = false) => {
  if (newData || !tempSearchForm) {
    tempSearchForm = JSON.parse(JSON.stringify(searchForm))
  }
  dataListLoading.value = true
  http({
    url: http.adornUrl('/platform/discount/page'),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        {
          shopName: searchForm.searchForm,
          current: pageParam == null ? page.currentPage : pageParam.currentPage,
          size: pageParam == null ? page.pageSize : pageParam.pageSize
        },
        tempSearchForm
      )
    )
  })
    .then(({ data }) => {
      dataList.value = data.records
      page.total = data.total
      dataListLoading.value = false

      // 末尾页数据为空重新请求
      if (!dataList.value.length && page.currentPage > 1) {
        page.currentPage = 1
        getDataList()
      }
    })
}

const addOrUpdateVisible = ref(false)
const addOrUpdateRef = ref(null)
/**
 * 查看商品
 * @param id
 */
const showProds = (id) => {
  addOrUpdateVisible.value = true
  nextTick(() => {
    addOrUpdateRef.value?.showProd(id, 1)
  })
}

/**
 * 删除
 * @param id
 */
const onDelete = (id) => {
  ElMessageBox.confirm($t('scoreProdList.isDelete'), $t('remindPop.remind'), {
    confirmButtonText: $t('remindPop.confirm'),
    cancelButtonText: $t('remindPop.cancel'),
    type: 'warning'
  })
    .then(() => {
      http({
        url: http.adornUrl(`/platform/discount/${id}`),
        method: 'delete',
        data: http.adornData({}, false)
      })
        .then(() => {
          ElMessage({
            message: $t('publics.operation'),
            type: 'success',
            duration: 1500,
            onClose: () => {
              getDataList(page)
            }
          })
        })
    })
}

const discountInfoRef = ref(null)
/**
 * 条件查询
 * @param newData
 */
const onSearch = (newData = false) => {
  page.currentPage = 1
  getDataList(page, newData)
}

const discountInfoVisible = ref(false)
const showDiscountInfoHandle = (id) => {
  discountInfoVisible.value = true
  nextTick(() => {
    discountInfoRef.value?.init(id)
  })
}

/**
 * 更新数据
 */
const refreshChange = () => {
  getDataList()
}

/**
 * 下架活动
 * @param row
 */
const offlineDiscountHandle = (row) => {
  // '确定对活动[' + row.discountName + ']进行下架操作？如是，请填写下架理由'
  let tips = $t('seckill.offlineTip')
  tips = tips.replace('ACTIVITYNAME', row.discountName)
  ElMessageBox.prompt(tips, $t('text.tips'), {
    confirmButtonText: $t('coupon.confirm'),
    cancelButtonText: $t('coupon.cancel'),
    inputPattern: /\s\S+|S+\s|\S/, // 不能全为空格 空字符串
    inputErrorMessage: $t('seckill.offlineReasonTip'),
    inputValidator: (value) => {
      if (value.length > 100) {
        return $t('seckill.offlineReasonTip1')
      }
    }
  })
    .then((obj) => {
      http({
        url: http.adornUrl('/platform/discount/offline'),
        method: 'post',
        data: http.adornData({
          handleId: row.discountId,
          offlineReason: obj.value || null
        })
      })
        .then(() => {
          ElMessage({
            message: $t('publics.operation'),
            type: 'success',
            duration: 1500,
            onClose: () => {
              getDataList(page)
            }
          })
        })
    })
}

const clearSearch = () => {
  searchForm.shopName = null
  searchForm.discountName = null
  searchForm.status = null
}

/**
 * 每页数量变更
 * @param val
 */
const onPageSizeChange = (val) => {
  page.pageSize = val
  getDataList()
}

/**
 * 页数变更
 * @param val
 */
const onPageChange = (val) => {
  page.currentPage = val
  getDataList()
}

const discountAuditVisible = ref(false)
const discountAuditRef = ref(null)
/**
 * 弹窗处理
 * @param id
 */
const discountAuditHandle = (id) => {
  discountAuditVisible.value = true
  nextTick(() => {
    discountAuditRef.value?.init(id)
  })
}

</script>
